import { recordInitTree, saveTravgelArrangment } from '@/services/api/api-interview-record';
import {
  AudioOutlined,
  CarOutlined,
  SendOutlined,
  SnippetsOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  DrawerForm,
  ProCard,
  ProForm,
  ProFormCascader,
  ProFormDatePicker,
  ProFormGroup,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
  ProFormText,
  FormListActionType,
} from '@ant-design/pro-components';
import { Button, Card, Cascader, Form, message } from 'antd';
import moment from 'moment';
import React from 'react';
import { useRef, useState } from 'react';

interface AddTravelArrangementsProps {
  onRefurbish: () => void;
  planList: InterviewRecordData.planList;
  registrationInfo: InterviewRecordData.RegistrationInfo;
  id: string;
}
const AddTravelArrangements: React.FC<AddTravelArrangementsProps> = ({
  onRefurbish,
  id,
  planList,
  registrationInfo,
}) => {
  const planActionRef = useRef<FormListActionType<{ name: string }>>();

  const formRef = useRef<ProFormInstance>();
  const assignOrganizationRef = useRef<FormListActionType<{ name: string }>>();
  const [activeKeys, setActiveKeys] = useState({}); // 存储每个出行安排的activeKey状态
  const [tabKeys, setTabKeys] = useState(['cars', 'media', 'organization']);
  const [mediaOptions, setMediaOptions] = useState();
  const [organizationOptions, setOrganizationOptions] = useState();

  const [tab, setTab] = useState('cars');
  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          // children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 媒体单位
   */
  const loadInitMediaOptions = async () => {
    try {
      const response = await recordInitTree({ type: 0 });
      if (response.code === 0) {
        setMediaOptions(readyTreeData(response.data));
      }
    } catch (error) {}
  };
  /**
   * 加载 采访单位
   */
  const loadInitAssignOrganizationOptions = async () => {
    try {
      const response = await recordInitTree({ type: 1 });
      if (response.code === 0) {
        setOrganizationOptions(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  const handleTabChange = (index, key) => {
    setActiveKeys((prev) => ({
      ...prev,
      [index]: key, // 更新对应出行安排的activeKey
    }));
  };

  return (
    <DrawerForm
      title="出行安排"
      trigger={
        <Button
          type="primary"
          style={{
            background: '#87d068',
          }}
        >
          <SendOutlined />
          出行安排
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: '100%',
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        const res = await saveTravgelArrangment({
          recordId: id,
          ...values,
        });
        if (res.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          message.error('提交失败');
          return false;
        }
        onRefurbish();
      }}
      onVisibleChange={(visible) => {
        if (visible) {
          //加载选择媒体
          loadInitMediaOptions();
          loadInitAssignOrganizationOptions();
        }
      }}
    >
      <ProFormList
        min={1}
        name="planList"
        actionRef={planActionRef}
        initialValue={
          Array.isArray(planList) && planList.length > 0
            ? planList
            : registrationInfo.length > 0
            ? registrationInfo
            : [{ leader: '' }] // 默认情况，确保始终有一行显示
        }
        label={
          <div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
            <span style={{ fontSize: 16 }}>
              <SnippetsOutlined style={{ marginRight: 5 }} />
              出行安排
            </span>
            <Button
              type="primary"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
              onClick={() => {
                planActionRef.current?.add(registrationInfo[0]);
              }}
            >
              添加出行安排
            </Button>
          </div>
        }
        actionGuard={{
          beforeAddRow: async (defaultValue, insertIndex) => {
            return new Promise((resolve) => {
              console.log(defaultValue, insertIndex);
              setTimeout(() => resolve(true), 500);
            });
          },
          beforeRemoveRow: async (index) => {
            return new Promise((resolve) => {
              if (index === 0) {
                message.error('这行不能删');
                resolve(false);
                return;
              }
              setTimeout(() => resolve(true), 500);
            });
          },
        }}
        creatorRecord={registrationInfo[0]}
        creatorButtonProps={{
          creatorButtonText: '添加出行安排',
        }}
        itemRender={({ listDom, action }, { index }) => {
          const currentActiveKey = activeKeys[index] || tabKeys[0];
          const planIndex = index;
          const carsActionRef = useRef<FormListActionType<{ name: string }>>();
          const mediaActionRef = useRef<FormListActionType<{ name: string }>>();
          const intervieweeRef = useRef<FormListActionType<{ name: string }>>();
          return (
            <ProCard
              bordered
              extra={action}
              title={`出行安排${index + 1}`}
              style={{
                marginBlockEnd: 8,
                display: 'flex',
                flexDirection: 'column',
              }}
            >
              <ProFormGroup key="group">
                <ProFormText name="leader" label="带队人员" width="sm" />
                <ProFormText
                  width="sm"
                  name="phone"
                  label="联系电话"
                  rules={[
                    {
                      pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                      message: '请输入正确的手机号',
                    },
                  ]}
                />
                <ProFormDatePicker
                  name="travelTime"
                  width="sm"
                  label="集中采访时间"
                  fieldProps={{
                    // disabledDate: (current) => current && current < moment().endOf('day'),
                    format: 'YYYY-MM-DD HH:mm:ss',
                  }}
                />
                <ProFormText name="address" label="采访地点" width="sm" />
              </ProFormGroup>
              <ProFormDatePicker
                name="presentationTime"
                width="lg"
                label="发布会时间"
                fieldProps={{
                  // disabledDate: (current) => current && current < moment(Array.isArray(formRef.current?.getFieldsValue()?.planList) && formRef.current?.getFieldsValue()?.planList[index].travelTime),
                  format: 'YYYY-MM-DD HH:mm:ss',
                }}
              />
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                <Card
                  bordered={false}
                  tabList={[
                    {
                      tab: (
                        <span>
                          <AudioOutlined style={{ marginRight: 5 }} />
                          媒体信息
                        </span>
                      ),
                      key: 'media',
                    },
                    {
                      tab: (
                        <span>
                          <UserOutlined style={{ marginRight: 5 }} />
                          采访对象
                        </span>
                      ),
                      key: 'organization',
                    },
                    {
                      tab: (
                        <span>
                          <CarOutlined style={{ marginRight: 5 }} />
                          车辆安排
                        </span>
                      ),
                      key: 'cars',
                    },
                  ]}
                  style={{ width: '100%' }}
                  activeTabKey={currentActiveKey}
                  onTabChange={(key) => handleTabChange(index, key)}
                  tabProps={{
                    size: 'middle',
                  }}
                />
                {currentActiveKey === 'cars' && (
                  <ProFormList
                    min={1}
                    style={{ paddingInline: 10 }}
                    name="carsList"
                    actionRef={carsActionRef}
                    label={
                      <div
                        style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}
                      >
                        <span>
                          <CarOutlined style={{ marginRight: 5 }} />
                          车辆信息
                        </span>
                        <Button
                          type="primary"
                          style={{ display: 'flex', justifyContent: 'flex-end' }}
                          onClick={() => {
                            carsActionRef.current?.add({
                              name: '',
                            });
                          }}
                        >
                          添加车辆信息
                        </Button>
                      </div>
                    }
                    initialValue={[
                      {
                        name: '',
                      },
                    ]}
                    creatorButtonProps={false}
                    actionGuard={{
                      beforeRemoveRow: async (index) => {
                        return new Promise((resolve) => {
                          if (index === 0) {
                            message.error('这行不能删');
                            resolve(false);
                            return;
                          }
                          setTimeout(() => resolve(true), 500);
                        });
                      },
                    }}
                    itemContainerRender={(doms) => {
                      return <ProForm.Group>{doms}</ProForm.Group>;
                    }}
                  >
                    {(f, index, action) => {
                      return (
                        <>
                          <ProFormText name="number" label="车牌" width="sm" />
                          <ProFormText name="name" label="司机" width={120} />
                          <ProFormText
                            name="phone"
                            label="电话"
                            rules={[
                              {
                                pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                                message: '请输入正确的手机号',
                              },
                            ]}
                          />
                        </>
                      );
                    }}
                  </ProFormList>
                )}

                {currentActiveKey === 'media' && (
                  <ProFormList
                    min={1}
                    style={{ paddingInline: 10 }}
                    name="mediaList"
                    // creatorButtonProps={false}
                    creatorButtonProps={{
                      creatorButtonText: '添加媒体信息',
                    }}
                    label={
                      <div
                        style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}
                      >
                        <span>
                          <AudioOutlined style={{ marginRight: 5 }} />
                          媒体信息
                        </span>
                        <Button
                          type="primary"
                          style={{ display: 'flex', justifyContent: 'flex-end' }}
                          onClick={() => {
                            mediaActionRef.current?.add({
                              name: '',
                              reporterList: [],
                            });
                          }}
                        >
                          添加媒体信息
                        </Button>
                      </div>
                    }
                    actionRef={mediaActionRef}
                    // initialValue={Array.isArray(mediaInfo) && mediaInfo.length > 0 ? mediaInfo : [{ name: '', reporterList: [{ name: '' }] }]}
                    itemRender={({ listDom, action }, { index }) => {
                      // const reporterActionRef = React.useRef(); // 为每个媒体条目创建新的 actionRef
                      const reporterActionRef = useRef<FormListActionType<{ name: string }>>();
                      const reporterActionRefAdd = useRef<FormListActionType<{ name: string }>>();
                      // 处理单位更改，清空记者信息

                      const handleOrganizationChange = (value) => {
                        // // 清空当前记者列表

                        // 假设 listDom 结构中包含每个记者信息时为一个特定的组件
                        const planlist =
                          Array.isArray(planList) && planList.length > 0
                            ? planList
                            : registrationInfo.length > 0
                            ? registrationInfo
                            : [{ leader: '' }];

                        if (planlist.length >= 1) {
                          const list = planlist[planIndex]?.mediaList[index]?.reporterList;

                          const length = Array.isArray(list) && list.length;

                          if (length && length > 0) {
                            for (let index = 0; index <= length; index++) {
                              reporterActionRef.current?.remove?.(0);
                            }
                          }
                        }
                      };
                      return (
                        <ProCard
                          bordered
                          extra={action}
                          title={`媒体${index + 1}`}
                          style={{
                            marginBlockEnd: 8,
                          }}
                        >
                          {listDom}
                          <ProFormSelect
                            width="lg"
                            label="单位"
                            name="organizationId"
                            showSearch
                            placeholder="选择单位"
                            options={mediaOptions}
                            // disabled
                            onChange={handleOrganizationChange} // 修改单位时清空记者信息
                          />
                          <ProFormList
                            name="reporterList"
                            actionRef={reporterActionRef} // 使用独立的 actionRef
                            creatorButtonProps={false}
                            label={
                              <div
                                style={{
                                  display: 'flex',
                                  justifyContent: 'space-between',
                                  width: '100vw',
                                }}
                              >
                                <span style={{ fontSize: 16 }}>记者信息</span>
                                <Button
                                  type="primary"
                                  style={{ display: 'flex', justifyContent: 'flex-end' }}
                                  onClick={() => {
                                    reporterActionRefAdd.current?.add({
                                      // 使用独立的 actionRef
                                      name: '',
                                    });
                                  }}
                                >
                                  添加记者信息
                                </Button>
                              </div>
                            }
                          >
                            <ProFormGroup key="group">
                              <ProFormText
                                name="name"
                                label="姓名"
                                width={120}
                                placeholder="请输入姓名"
                                disabled
                              />
                              <ProFormText
                                name="phone"
                                label="电话"
                                placeholder="请输入电话"
                                rules={[
                                  {
                                    pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                                    message: '请输入正确的手机号',
                                  },
                                ]}
                              />
                            </ProFormGroup>
                          </ProFormList>
                          <ProFormList
                            name="reporterListAdd"
                            actionRef={reporterActionRefAdd} // 使用独立的 actionRef
                            creatorButtonProps={false}
                          >
                            <ProFormGroup key="group">
                              <ProFormText
                                name="name"
                                label="姓名"
                                width={120}
                                placeholder="请输入姓名"
                                required
                                rules={[{ required: true, message: '姓名不能为空' }]}
                              />
                              <ProFormText
                                name="phone"
                                label="电话"
                                placeholder="请输入电话"
                                rules={[
                                  {
                                    pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                                    message: '请输入正确的手机号',
                                  },
                                ]}
                              />
                            </ProFormGroup>
                          </ProFormList>
                        </ProCard>
                      );
                    }}
                  />
                )}
                {currentActiveKey === 'organization' && (
                  <ProFormList
                    min={1}
                    style={{ paddingInline: 10 }}
                    name="assignOrganizationList"
                    // creatorButtonProps={false}
                    creatorButtonProps={{
                      creatorButtonText: '添加采访对象',
                    }}
                    label={
                      <div
                        style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}
                      >
                        <span>
                          <UserOutlined style={{ marginRight: 5 }} />
                          采访对象
                        </span>
                        <Button
                          type="primary"
                          style={{ display: 'flex', justifyContent: 'flex-end' }}
                          onClick={() => {
                            intervieweeRef.current?.add({
                              name: '',
                              organizationList: [],
                            });
                          }}
                        >
                          添加采访对象
                        </Button>
                      </div>
                    }
                    actionRef={intervieweeRef}
                    // initialValue={Array.isArray(planList[index].assignOrganizationList) && planList[index].assignOrganizationList.length > 0 ? planList[index].assignOrganizationList : [{ name: '', organizationList: [{ name: '' }] }]}
                    itemRender={({ listDom, action }, { index }) => {
                      const assignOrganizationRef = useRef<FormListActionType<{ name: string }>>();
                      const assignOrganizationRefAdd =
                        useRef<FormListActionType<{ name: string }>>();
                      // 处理单位更改，清空记者信息
                      const handleOrganizationChange = (value) => {
                        // // 清空当前记者列表

                        // 假设 listDom 结构中包含每个记者信息时为一个特定的组件
                        const planlist =
                          Array.isArray(planList) && planList.length > 0
                            ? planList
                            : registrationInfo.length > 0
                            ? registrationInfo
                            : [{ leader: '' }];
                        console.log(planlist);

                        if (planlist.length >= 1) {
                          const list =
                            planlist[planIndex]?.assignOrganizationList[index]?.organizationList;

                          const length = Array.isArray(list) && list.length;

                          if (length && length > 0) {
                            for (let index = 0; index <= length; index++) {
                              assignOrganizationRef.current?.remove?.(0);
                            }
                          }
                        }
                      };
                      return (
                        <ProCard
                          bordered
                          extra={action}
                          title={`采访对象${index + 1}`}
                          style={{
                            marginBlockEnd: 8,
                          }}
                        >
                          {listDom}
                          <ProFormSelect
                            width="lg"
                            label="单位"
                            name="organizationId"
                            showSearch
                            placeholder="选择单位"
                            options={organizationOptions}
                            onChange={handleOrganizationChange}
                          />

                          <ProFormList
                            name="organizationList"
                            actionRef={assignOrganizationRef}
                            creatorButtonProps={false}
                            label={
                              <div
                                style={{
                                  display: 'flex',
                                  justifyContent: 'space-between',
                                  width: '100vw',
                                }}
                              >
                                <span style={{ fontSize: 16 }}>联络人信息</span>
                                <Button
                                  type="primary"
                                  style={{ display: 'flex', justifyContent: 'flex-end' }}
                                  onClick={() => {
                                    assignOrganizationRefAdd.current?.add({
                                      name: '',
                                    });
                                  }}
                                >
                                  添加联络人信息
                                </Button>
                              </div>
                            }
                          >
                            <ProFormGroup key="group">
                              <ProFormText name="name" label="姓名" width={120} disabled />
                              <ProFormText
                                name="phone"
                                label="电话"
                                rules={[
                                  {
                                    pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                                    message: '请输入正确的手机号',
                                  },
                                ]}
                              />
                            </ProFormGroup>
                          </ProFormList>
                          <ProFormList
                            name="organizationListAdd"
                            actionRef={assignOrganizationRefAdd}
                            creatorButtonProps={false}
                          >
                            <ProFormGroup key="group">
                              <ProFormText
                                name="name"
                                label="姓名"
                                width={120}
                                required
                                rules={[{ required: true, message: '姓名不能为空' }]}
                              />
                              <ProFormText
                                name="phone"
                                label="电话"
                                rules={[
                                  {
                                    pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                                    message: '请输入正确的手机号',
                                  },
                                ]}
                              />
                            </ProFormGroup>
                          </ProFormList>
                        </ProCard>
                      );
                    }}
                  ></ProFormList>
                )}
              </div>
            </ProCard>
          );
        }}
      ></ProFormList>
    </DrawerForm>
  );
};

export default AddTravelArrangements;
